<template>
  <div class="resume-upload">
    <h1 class="title">AI简历诊断,轻松get offer</h1>
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          
          <p class="sub-title">请上传您的简历开始分析</p>
        </div>
      </template>

      <div class="selection-section">
        <div class="action-buttons">
          <el-button type="primary" size="large" @click="showUploadSection = true; showCard = false">
            <el-icon><Upload /></el-icon>
            <span>上传简历</span>
          </el-button>
          <el-button plain size="large" @click="checkProfileResume">
            <el-icon><User /></el-icon>
            <span>使用个人简历</span>
          </el-button>
        </div>

        <el-upload
          v-if="showUploadSection"
          class="upload-demo"
          drag
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">支持 PDF/JPEG/PNG 格式，大小不超过 5MB</div>
          </template>
        </el-upload>

        


        <el-dialog v-model="showJdDialog" title="职位描述编辑" :width="dialogWidth" top="5vh">
          <div class="rich-editor-wrapper">
            <span style="margin-left: 10px;"> 填写职位描述分析更准确（可跳过） </span>

            <div
              class="editor-content"
              ref="editor"
              contenteditable="true"
              @paste="handlePaste"
              @dragover.prevent
              @drop.prevent="handleDrop"
              placeholder="可直接描述"
            ></div>
          </div>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="goToDiagnosis">跳过</el-button>
              <el-button type="primary" @click="handleSubmit">分析</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </el-card>
    
    <div class="card" v-if="showCard">
          <div class="card__border"></div>
          <div class="card_title__container">
            <!-- <span class="card_title"></span> -->
          </div>
          <ul class="card__list">
            <li class="card__list_item">
              <span class="check">
                <svg
                  class="check_svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    clip-rule="evenodd"
                    d="M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z"
                    fill-rule="evenodd"
                  ></path>
                </svg>
              </span>
              <span class="list_text">排版美观，简洁易懂;</span>
            </li>
            <li class="card__list_item">
              <span class="check">
                <svg
                  class="check_svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    clip-rule="evenodd"
                    d="M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z"
                    fill-rule="evenodd"
                  ></path>
                </svg>
              </span>
              <span class="list_text">数据客观，成果量化;</span>
            </li>
            <li class="card__list_item">
              <span class="check">
                <svg
                  class="check_svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    clip-rule="evenodd"
                    d="M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z"
                    fill-rule="evenodd"
                  ></path>
                </svg>
              </span>
              <span class="list_text">条例清晰，主次分明;</span>
            </li>
            <li class="card__list_item">
              <span class="check">
                <svg
                  class="check_svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    clip-rule="evenodd"
                    d="M12.416 3.376a.75.75 0 0 1 .208 1.04l-5 7.5a.75.75 0 0 1-1.154.114l-3-3a.75.75 0 0 1 1.06-1.06l2.353 2.353 4.493-6.74a.75.75 0 0 1 1.04-.207Z"
                    fill-rule="evenodd"
                  ></path>
                </svg>
              </span>
              <span class="list_text">优势突出，正对性强;</span>
            </li>
          </ul>
        </div>
    <TabNav /> 

  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive  } from 'vue'
import { ElMessage } from 'element-plus'
import Tesseract from 'tesseract.js'
import { useRouter } from 'vue-router'
import { resumeApi } from '@/views/resume/api/index.js'
import TabNav from '@/components/TabNav/TabNav.vue'

const router = useRouter()
const showUploadSection = ref(false)
const showJdDialog = ref(false)
const dialogWidth = ref('800px')
const editor = ref(null)
const ocrLoading = ref(false)
const showCard = ref(true)

// deepseek的建议
const aiContent = reactive({
  content: '',
  loading: false
})

// 自适应处理
const updateDialogWidth = () => {
  const windowWidth = window.innerWidth
  dialogWidth.value = windowWidth < 768 ? '90%' 
                     : windowWidth < 1200 ? '70%' 
                     : '800px'
}

onMounted(() => {
  updateDialogWidth()
  window.addEventListener('resize', updateDialogWidth)
  initEditorStyle()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateDialogWidth)
})

const initEditorStyle = () => {
  if (editor.value) {
    editor.value.style.minHeight = '40vh'
    editor.value.style.maxHeight = '60vh'
    editor.value.style.padding = '2vh 2vw'
    editor.value.style.border = '1px solid #EBEEF5'
    editor.value.style.borderRadius = '4px'
    editor.value.style.overflowY = 'auto'
  }
}
// 处理图片,获取图片文字
const handleImage = async (file) => {
  const imgUrl = URL.createObjectURL(file) // 创建一个临时URL
  try {
    insertImageElement(imgUrl)
    ocrLoading.value = true // 显示加载状态
    const { data: { text } } = await Tesseract.recognize(file, 'chi_sim+eng')
    insertText(`\n${text}\n`)
  } catch (error) {
    ElMessage.error(`识别失败: ${error.message}`)
  } finally {
    ocrLoading.value = false
    URL.revokeObjectURL(imgUrl) // 释放内存
  }
}
// 插入图片和文字
const insertImageElement = (url) => {
  const img = document.createElement('img')
  img.src = url
  img.style.maxWidth = '100%'
  editor.value.appendChild(img)
}

// 插入文字
const insertText = (text) => {
  const p = document.createElement('p')
  p.textContent = text
  editor.value.appendChild(p)
}
// 处理粘贴事件
const handlePaste = async (e) => {
  const items = e.clipboardData.items // 获取粘贴板中的所有项
  for (const item of items) {
    // 检查是否为图片
    if (item.type.startsWith('image/')) {
      await handleImage(item.getAsFile())
      e.preventDefault() 
    }
  }
}

// 处理拖拽事件
const handleDrop = async (e) => {
  const file = e.dataTransfer.files[0]
  if (file?.type.startsWith('image/')) {
    await handleImage(file)
    e.preventDefault()
  }
}

// 处理提交事件
const handleSubmit = async () => {
  try {
    const content = {
      text: editor.value.innerText,
      images: [...editor.value.querySelectorAll('img')].map(img => img.src)
    }
    await resumeApi.submitJobDescription(content)
    router.push(
      {path: '/diagnosisResults'},
      {query: {jd: aiContent.content}}
    )
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message)
  }
}
const goToDiagnosis = async () => {
  router.push(
    {path: '/diagnosisResults'},
    {query: {jd: aiContent.content}}
  )
}

const checkProfileResume = async () => {
  try {
    const { data } = await resumeApi.checkProfile()
    console.log("查找简历"+data)
    if (data.exists) {
      aiContent.content = data.content // 查找到的简历内容
      showJdDialog.value = true
    }else {
      ElMessage.warning('未找到简历')
    } 
  }
  catch (error) {
    ElMessage.error('检查失败: ' + error.message)
  }
}

// 上传简历
const handleFileChange = async ({ raw: file }) => {
  if (!validateResume(file)) return
  try {
    console.log('file', file)
    aiContent.content = await resumeApi.upload(file)
    console.log("aiContent"+aiContent.content)
    showJdDialog.value = true
  } catch (error) {
    ElMessage.error('上传失败: ' + error.message)
  }
}

const validateResume = (file) => {
  const validTypes = ['image/jpeg', 'image/png', 'application/pdf']
  const maxSizeMB = 5
  if (!validTypes.includes(file.type)) return ElMessage.error('仅支持 JPG/PNG/PDF 格式')
  if (file.size / 1024 / 1024 > maxSizeMB) return ElMessage.error(`文件大小不能超过${maxSizeMB}MB`)
  return true
}
</script>

<style lang="scss" scoped>

h1 {
  font-weight: 700;
  text-align: center;
  margin-bottom: 16px;
}
.resume-upload {
  display: flex;
  flex-direction: column; 
  justify-content: center; 
  align-items: center; 
  height: 100vh; /* 视口高度 */
  background: linear-gradient(
    135deg,
    #ffe8f3,
    #d9f3ff
  ); 
  padding: 20px;
  box-sizing: border-box;

  .upload-card {
    width: 100%;
    max-width: 400px; 
    background: #fff;
    border: 6px solid #8fb5e7;
    box-shadow: 12px 12px 0 #cae2ff;
    border-radius: 12px;
    text-align: center;
    box-sizing: border-box;

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-bottom: 24px;
    }

    .el-upload {
      width: 100%;
      text-align: center;

      .el-upload-dragger {
        width: 100%;
        height: 180px;
        border: 2px dashed #b1cbed;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 0.9);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }

      .el-upload__text {
        margin-top: 16px;
        color: #666;
      }

      .el-upload__tip {
        margin-top: 8px;
        color: #999;
        font-size: 12px;
      }
    }
  }

  .el-dialog {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
    width: 90%; /* 设置宽度，避免过长 */
    max-width: 600px; /* 设置最大宽度 */
  }

  .rich-editor-wrapper {
    .editor-content {
      min-height: 200px;
      padding: 16px;
      border: 1px solid #EBEEF5;
      border-radius: 4px;
      line-height: 1.6;
      overflow-y: auto;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
  }
}

.card {
  --white: hsl(0, 0%, 0%);
  --black: hsl(207, 95%, 69%);
  --paragraph: hsl(0, 0%, 83%);
  --primary: #d4e7ff;

  position: relative;

  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 50px;

  padding: 1rem;
  width: 19rem;
  // background-color: rgb(182, 211, 255);
  border:#8fb5e7 4px solid;
  border-radius: 1rem;
}

.card .card__border {
  overflow: hidden;
  pointer-events: none;

  position: absolute;
  z-index: -10;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  width: calc(100% + 2px);
  height: calc(100% + 2px);

  border-radius: 1rem;
}

.card .card__border::before {
  content: "";
  pointer-events: none;

  position: fixed;
  z-index: 200;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%), rotate(0deg);
  transform-origin: left;
}

.card .card_title__container .card_title {
  font-size: 20px;
  color: var(--white);
}

.card .card__list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.card .card__list .card__list_item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.card .card__list .card__list_item .list_text{
  color: #59a1ff;
  font-size: 1.2rem;
}

.card .card__list .card__list_item .check {
  display: flex;
  justify-content: center;
  align-items: center;

  width: 1rem;
  height: 1rem;
  background-color: var(--primary);

  border-radius: 50%;
}

.card .card__list .card__list_item .check .check_svg {
  width: 0.75rem;
  height: 0.75rem;

  fill: var(--black);
}

</style>